import { isTypeOf } from './types';

/**
 * 多维数组展开
 * @param arr
 * @returns
 */
export const unfoldArr = (arr: any[]): any[] => {
  return arr.reduce((prev, next) => {
    return prev.concat(isTypeOf(next, 'Array') ? unfoldArr(next) : next);
  }, []);
};
/**
 * 过滤出字符串中的目标文本
 * @param text    文本
 * @param target  目标文本
 * @returns
 */
export const getTargetText = (text: string, target: string[]): string[] => {
  return target.filter((item) => text.includes(item));
};

/**
 * 产生在m、n之间的随机整数
 * @param m 开始
 * @param n 结束
 * @returns
 */
export const random = (m: number, n: number): number => {
  return Math.round(Math.random() * (n - m)) + m;
};
/**
 * 产生随机索引
 * @param length
 * @param n
 * @returns
 */
export const randomIndexS = (length: number, n: number): number[] => {
  const result = new Array(length);
  let index = -1;
  while (++index < length) {
    result[index] = index;
  }
  return result.sort(() => Math.random() - 0.5).slice(0, n);
};
/**
 * 文本中的随机组合
 * @param txt
 * @param number
 */
export const randomTxt = (txtList: string[], number: number): string => {
  const indexS = randomIndexS(txtList.length, number);
  const data = indexS.map((i) => txtList[i]);
  return data.join('');
};
/**
 * 随机文本库
 * @param type 
 * @param number 
 * @returns 
 */
export const randomTxtLibrary = (type:string, number: number): string => {
  const library = {
    uppercase: 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
    lowercase: 'abcdefghijklmnopqrstuvwxyz',
    number: '0123456789',
  }
  const txtList = library[type].split('')
  return randomTxt(txtList, number);
}

// console.log(unfoldArr([1,2,[3,4]]));
// console.log(getTargetText('1345', ['1','2','3']));
// console.log(randomTxt('13456789', 4));